<!--
 * Description: 系统角色修改页面
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Dongxu.Ni
 * Date: 2020/03/19 02:57
-->

<template>
  <div v-loading="isRequesting">
    <!--数据表单-->
    <el-form label-width="100px" :model="formData" size="mini">
      <el-row>
        <el-col :span="24" style="padding: 0">
          <!--角色信息-->
          <el-form-item
            :label="$t('RoleManager.roleInfo')"
            style="background: #c9d2ca;text-align: right"
          />
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <!--角色名称-->
          <el-form-item :label="$t('RoleManager.roleName')">
            <el-input v-model="formData.roleName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!--父级岗位-->
          <el-form-item :label="$t('RoleManager.parentRolePost')">
            <el-select
              v-model="formData.parentRolePost"
              clearable
              disabled
              :placeholder="$t('select.placeholder')"
              style="width: 100%"
            >
              <el-option
                v-for="item in parentRolePostListOptions"
                :key="item.postId"
                :label="item.postName"
                :value="item.postId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <!--角色描述-->
          <el-form-item :label="$t('RoleManager.roleDesc')">
            <el-input v-model="formData.roleDesc" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="padding: 0">
          <!--关联菜单-->
          <el-form-item
            :label="$t('RoleManager.mapMenu')"
            style="background: #c9d2ca;text-align: right"
          />
        </el-col>
      </el-row>
      <el-row>
        <el-tree
          ref="roleEditTree"
          :data="currentPostMenuTree"
          :expand-on-click-node="false"
          :highlight-current="true"
          node-key="menuId"
          :props="{ children: 'children' }"
          show-checkbox
          @check-change="treeNodeCheckChange"
        >
          <span
            slot-scope="{ node, data }"
            style="flex: 1;display: flex;align-items: center;justify-content: space-between;font-size: 14px;padding-right: 8px;"
          >
            <span>{{ data.menuName }}</span>
            <span v-for="(item, index) in data.menuFuncList" :key="index">
              <span v-if="item.bindButton">
                <el-checkbox v-model="item.checked" :disabled="!node.checked">
                  <el-tag
                    effect="dark"
                    size="mini"
                    style="margin-right: 20px"
                    :type="item.checked ? 'success' : 'info'"
                  >
                    {{ $store.getters['dict/dictValue'](item.bindButton) }}
                  </el-tag>
                </el-checkbox>
              </span>
            </span>
          </span>
        </el-tree>
      </el-row>
    </el-form>
    <span style="display: block;text-align: center;margin-top: 5px">
      <!--取消按钮-->
      <el-button size="medium" @click="cancel">{{ $t('button.cancel') }}</el-button>
      <!--保存按钮-->
      <el-button size="medium" type="primary" @click="save">{{ $t('button.save') }}</el-button>
    </span>
  </div>
</template>

<script>
import { roleEdit, roleListMappingMenu } from '../../../../api/sys/role'
import { menuListFullByPost } from '../../../../api/sys/menu'
import { menuListToMenuTree } from '../../../../store/modules/menu'
import { getLangMappingProperty } from '../../../../lang/lang-set'

export default {
  name: 'RoleEdit',
  props: {
    inputData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      // 正在查询
      isRequesting: false,
      formData: {},
      currentPostMenuTree: []
    }
  },
  computed: {
    // 岗位列表
    parentRolePostListOptions() {
      return this.$store.getters['post/getSelfAndSubPostList']
    }
  },
  watch: {},
  created() {
    this.pageDataInit()
  },
  mounted() {},
  methods: {
    async pageDataInit() {
      try {
        this.isRequesting = true
        this.formData = JSON.parse(JSON.stringify(this.inputData))
        if (this.formData.parentRolePost === this.$store.getters['post/getSessionPostId']) {
          this.currentPostMenuTree = JSON.parse(
            JSON.stringify(this.$store.getters['menu/getSessionPostMenuTree'])
          )
          this.initRoleMenu()
        } else {
          const response = await menuListFullByPost({ postId: this.formData.parentRolePost })
          const menuList = response.data
          // 排序
          menuList.sort((a, b) => {
            return a.order - b.order
          })
          const language = this.$store.getters['language/getLanguage']
          const langMappingProperty = getLangMappingProperty(language, 'menuName')
          for (const tempMenu of menuList) {
            tempMenu.menuName = tempMenu[langMappingProperty]
          }
          this.currentPostMenuTree = menuListToMenuTree(menuList)
          this.initRoleMenu()
        }
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },
    treeNodeCheckChange(nodeData, checked) {
      if (checked) {
        return
      }
      const menuFuncList = nodeData.menuFuncList
      if (menuFuncList && menuFuncList.length > 0) {
        for (const menuFunc of menuFuncList) {
          menuFunc.checked = false
        }
      }
    },
    // 初始化角色的菜单
    async initRoleMenu() {
      try {
        this.isRequesting = true
        const response = await roleListMappingMenu({ roleId: this.formData.roleId })
        const roleMenuList = response.data
        for (const roleMenu of roleMenuList) {
          // 角色菜单功能三联列表
          const roleMenuFuncList = roleMenu.roleMenuFuncList
          this.$refs.roleEditTree.setChecked(roleMenu.menuId, true)
          const node = this.$refs.roleEditTree.getNode(roleMenu.menuId)
          // 存在功能选项
          if (roleMenuFuncList && roleMenuFuncList.length > 0) {
            for (const menuFunc of node.data.menuFuncList) {
              this.$set(menuFunc, 'checked', false)
              for (const roleMenuFunc of roleMenuFuncList) {
                if (menuFunc.funcId === roleMenuFunc.funcId) {
                  this.$set(menuFunc, 'checked', true)
                }
              }
            }
          }
        }
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },
    async save() {
      try {
        this.isRequesting = true
        const checkedMenuNodes = this.$refs.roleEditTree.getCheckedNodes(true)
        const roleMenuList = []
        for (const menuNode of checkedMenuNodes) {
          if (menuNode.isCatalog) {
            continue
          }
          const roleMenu = { roleId: this.formData.roleId, menuId: menuNode.menuId }
          const roleMenuFuncList = []
          let menuFuncList = menuNode.menuFuncList
          if (!menuFuncList) {
            menuFuncList = []
          }
          for (const menuFunc of menuFuncList) {
            if (menuFunc.checked) {
              roleMenuFuncList.push({
                roleId: this.formData.roleId,
                menuId: menuFunc.menuId,
                funcId: menuFunc.funcId,
                isHidden: false
              })
            }
          }
          roleMenu.roleMenuFuncList = roleMenuFuncList
          roleMenuList.push(roleMenu)
        }
        const data = { ...this.formData, roleMenuList }
        await roleEdit(data)
        this.$emit('save')
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },
    cancel() {
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped></style>
